package com.tyc.flink;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;
/**
 * Reduce KeyedStream → DataStream
 *
 * @author tyc
 * @version 1.0
 * @date 2022-11-16 17:50:13
 */
public class Transform_5_Reduce {

        public static void main(String[] args) throws Exception {
            StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
            env.setParallelism(1);
            DataStreamSource<String> dataStreamSource = env.fromCollection(
                    Arrays.asList("hello flink",
                            "hello java",
                            "hi program",
                            "hello",
                            "java"));

            // 1、分词
            // 2、按每个单词作为key分组
            // 3、使用reduce统计每个单词出现次数
            SingleOutputStreamOperator<Tuple2<String, Integer>> reduce = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                @Override
                public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                    String[] s1 = s.split(" ");
                    for (String s2 : s1) {
                        collector.collect(new Tuple2<>(s2, 1));
                    }
                }
            }).keyBy(item -> item.f0)
                    .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
                        @Override
                        public Tuple2<String, Integer> reduce(Tuple2<String, Integer> t1, Tuple2<String, Integer> t2) throws Exception {
                            System.out.println("---t1.f0:"+t1.f0 + ",---t2.f0:"+t2.f0);
                            System.out.println("---t1.f1:"+t1.f1 + ",---t2.f1:"+t2.f1);
                            return new Tuple2<String, Integer>(t1.f0,t1.f1+t2.f1);
                        }
                    });
            reduce.print();
            env.execute();
        }
}
